const app = getApp();
const util = require('../../utils/util.js')
Page({
  data: {
    imageUrl: app.globalData.imageUrl,
    goods_detail: {},
    adv_list: [],
    goods_body: [],
    showModalStatus: false,
    buynum: 1,
    cart_count: '',
    show_fly_img: false,
    key: '',
    goods_map_spec: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.share();
    var goods_id = options.goods_id || 108641;
    this.setData({
      goods_id
    })
    var self = this;
    wx.getStorage({
      key: 'key',
      success: res => {
        self.setData({
          key: res.data
        })
        self.getCartInfo();
      }
    })
    wx.getStorage({
      key: 'cart_count',
      success: (res) => {
        this.setData({
          cart_count: res.data
        })
      },
    })

    var ap_id = '39,40,41';
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=load_wap_adv&op=wechat',
      data: {
        ap_id: ap_id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success(res) {
        self.setData({
          adv_list: res.data.datas
        })
      }
    });
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=goods&op=goods_body&goods_id=' + goods_id + '&client_type=wechat',
      success(res) {
        self.setData({
          goods_body: res.data.datas
        })
      }
    });
    this.cartPos = {};
    this.cartPos['x'] = 86;
    this.cartPos['y'] = app.globalData.sh - 44;
  },
  onReady: function () {
    let self = this;
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=goods&op=goods_detail&goods_id=' + self.data.goods_id + '&key=' + self.data.key + '&client_type=wechat',
      success(resa) {
        let map_spec=resa.data.datas.goods_info.goods_map_spec;
        if(Object.keys(map_spec).length === 0){
          self.setData({
            goods_map_spec: false
          })
        }
        self.setData({
          goods_detail: resa.data.datas,
          is_favorite: resa.data.datas.is_favorate
        })
      }
    });
  },
  onShow: function (options) {
    if (!this.data.key) {
      wx.getStorage({
        key: 'key',
        success: res => {
          this.setData({
            key: res.data
          })
        }
      })
    }
  },
  addBuynum: function () {
    if (this.data.buynum < this.data.goods_detail.goods_info.goods_storage) {
      this.data.buynum++
    }
    this.setData({
      buynum: this.data.buynum
    })
  },
  buynumInput: function (e) {
    this.setData({
      buynum: e.detail.value
    })
  },
  cutBuynum: function () {
    if (this.data.buynum > 1) {
      this.data.buynum--;
      this.setData({
        buynum: this.data.buynum
      })
    }
  },
  buyStep1: function () {
    var self = this;
    if (this.data.buynum - this.data.goods_detail.goods_info.goods_storage > 0) {
      wx.showToast({
        title: '库存不足！',
        icon: 'none'
      })
      return;
    }
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=buy_step1',
      data: {
        key: self.data.key,
        cart_id: self.data.goods_detail.goods_info.goods_id + '|' + self.data.buynum
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if (res.data.login == '0') {
          if (app.globalData.authorized) {
            wx.navigateTo({
              url: "../chooselogin/chooselogin"
            })
          } else {
            wx.navigateTo({
              url: "../login/login"
            })
          }
        } else {
          wx.navigateTo({
            url: '../confirm_order/confirm_order?goods_id=' + self.data.goods_detail.goods_info.goods_id + '&buynum=' + self.data.buynum
          })
        }
      }
    })
  },
  add_Cart: function (e) {
    var self = this;
    let goods_img = e.currentTarget.dataset['goods_img'];
    this.setData({
      goodsImageFly: goods_img
    })
    let type = e.currentTarget.dataset.type;
    if (this.data.buynum - this.data.goods_detail.goods_info.goods_storage > 0) {
      wx.showToast({
        title: '库存不足！',
        icon: 'none'
      })
      return;
    }
    let goods_id = self.data.goods_detail.goods_info.goods_id;
    let quantity = self.data.buynum;
    wx.getStorage({
      key: 'key',
      success: (res) => {
        wx.request({
          url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=wechat_cart_add',
          data: {
            key: res.data,
            goods_id: goods_id,
            quantity: quantity
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          dataType: 'json',
          success: (res) => {
            if (res.data.code == 200) {
              wx.getStorage({
                key: 'cart_count',
                success: (res) => {
                  wx.setTabBarBadge({
                    index: 3,
                    text: String(res.data + quantity)
                  })
                  wx.setStorage({
                    key: 'cart_count',
                    data: res.data + quantity
                  })
                  self.setData({
                    cart_count: self.data.cart_count + self.data.buynum
                  })
                  self.addcartAnimation(e, type);
                },
              })
            } else {
              wx.showToast({
                title: res.data.datas.error,
                icon: 'none'
              })
            }
          }
        });
      },
      fail: () => {
        if (app.globalData.authorized) {
          wx.navigateTo({
            url: "../chooselogin/chooselogin"
          })
        } else {
          wx.navigateTo({
            url: "../login/login"
          })
        }
      }
    })




  },
  addcartAnimation: function (e, type) {
    if (this.data.show_fly_img)
      return;
    this.finger = {};
    var topPoint = {};
    if (type == 'self') {
      this.finger['x'] = 20;
      this.finger['y'] = 200;
    } else {
      this.finger['x'] = e.touches["0"].clientX - 50;
      this.finger['y'] = e.touches["0"].clientY - 100;
    }
    if (this.finger['x'] - this.cartPos['x'] < 0) {
      topPoint['x'] = (this.cartPos['x'] - this.finger['x']) / 2 + this.finger['x'];
    } else {
      topPoint['x'] = Math.abs(this.cartPos['x'] - this.finger['x']) / 2 + this.cartPos['x'];
    }
    if (this.finger['y'] < this.cartPos['y']) {
      topPoint['y'] = this.finger['y'] - 80;
    } else {
      topPoint['y'] = this.cartPos['y'] - 80;
    }
    this.linePos = app.bezier([this.finger, topPoint, this.cartPos], 30);
    this.startAnimation();
  },
  startAnimation: function () {
    var index = 0,
      self = this,
      bezier_points = this.linePos['bezier_points'];
    this.setData({
      show_fly_img: true,
      fly_x: self.finger['x'],
      fly_y: self.finger['y']
    })
    this.timer = setInterval(() => {
      self.setData({
        fly_x: bezier_points[index]['x'],
        fly_y: bezier_points[index]['y']
      })
      index++;
      if (index >= 30) {
        clearInterval(self.timer);
        self.setData({
          show_fly_img: false
        })
      }
    }, 22);
  },
  gotoCart: function () {
    wx.switchTab({
      url: '../cart/cart'
    })
  },
  goodsUp: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function (currentStatu) {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
      delay: 0,
    });
    this.animation = animation;
    animation.translateY(400).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  changeType: function (e) {
    var specsValueId = e.currentTarget.dataset.specs_value_id;
    var spec_list = this.data.goods_detail.spec_list;
    var curKey;
    var curValue;
    for (let key in spec_list) {
      if (key.indexOf(specsValueId) >= 0) {
        curKey = key;
        curValue = spec_list[key];
      }
    }
    var goods_id = curValue;
    var self = this;
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=goods&op=goods_detail&goods_id=' + goods_id + '&client_type=wechat',
      success(res) {
        self.setData({
          goods_detail: res.data.datas
        })
      }
    });
  },
  collectGoods: function (e) {
    var self = this;
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=member_favorites&op=favorites_add',
      data: {
        goods_id: goods_id,
        key: self.data.key
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success(res) {
        if (res.data.code == 200) {
          self.setData({
            is_favorite: true
          })
        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
        }
      }
    });
  },
  collectGoodsCancel: function (e) {
    var self = this;
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=member_favorites&op=favorites_del',
      data: {
        fav_id: goods_id,
        key: self.data.key
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success(res) {
        if (res.data.code == 200) {
          self.setData({
            is_favorite: false
          })
        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
        }
      }
    });
  },
  custormerService: function () {
    wx.navigateTo({
      url: this.data.key ? `../message_detail/message_detail?store_name=${this.data.goods_detail.store_info.store_name}&avatar=${this.data.goods_detail.store_info.store_avatar}` : '../chooselogin/chooselogin'
    })
  },
  contactStore: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.goods_detail.store_info.store_phone
    })
  },
  getCartInfo: function () {
    var self = this;
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_list',
      data: {
        key: self.data.key
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      success: res => {
        if (res.data.code == '200') {
          self.setData({
            cart_list: res.data.datas.cart_list
          })
          var selfGoods = {};
          var arrtemp = new Array();
          for (let i = 0; i < 20; i++) {
            arrtemp[i] = new Object();
          }
          for (let i = 0; i < self.data.cart_list.length; i++) {
            for (let j = 0; j < self.data.cart_list[i].goods.length; j++) {
              selfGoods[self.data.cart_list[i].goods[j].goods_id] = {
                cart_id: self.data.cart_list[i].goods[j].cart_id,
                goods_num: self.data.cart_list[i].goods[j].goods_num
              }
            }
          }
          self.setData({
            cartGoods: selfGoods
          })
        }
      }
    })
  },
  addCart: function (e) {
    let self = this;
    let goods_id = e.currentTarget.dataset['goods_id'];
    let quantity = 1;
    let addQuantity = 0;
    let goods_img = e.currentTarget.dataset['goods_img'];
    if (this.data.cartGoods[goods_id]) {
      addQuantity = this.data.cartGoods[goods_id].goods_num * 1 + 1;
    } else {
      addQuantity = 1
    }
    this.setData({
      goodsImageFly: goods_img
    })
    wx.getStorage({
      key: 'key',
      success: (res) => {
        wx.request({
          url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_add_edit',
          data: {
            key: res.data,
            goods_id: goods_id,
            quantity: addQuantity
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          dataType: 'json',
          success: (res) => {
            if (res.data.code == 200) {
              wx.getStorage({
                key: 'cart_count',
                success: (res) => {
                  wx.setTabBarBadge({
                    index: 3,
                    text: String(res.data + quantity)
                  })
                  wx.setStorage({
                    key: 'cart_count',
                    data: res.data + quantity
                  })
                },
              })
              self.addcartAnimation(e);
              self.setData({
                cart_count: self.data.cart_count + 1
              })
              if (this.data.cartGoods[goods_id]) {
                self.data.cartGoods[goods_id].goods_num++;
                self.setData({
                  cartGoods: self.data.cartGoods
                })
              } else {
                self.data.cartGoods[goods_id] = {
                  cart_id: res.data.datas,
                  goods_num: 1
                }
                self.setData({
                  cartGoods: self.data.cartGoods
                })
              }

            } else {
              wx.showToast({
                title: res.data.datas.error,
                icon: 'none'
              })
            }
          }
        });
      },
      fail: () => {
        if (app.globalData.authorized) {
          wx.navigateTo({
            url: "../chooselogin/chooselogin"
          })
        } else {
          wx.navigateTo({
            url: "../login/login"
          })
        }
      }
    })
  },
  onShareAppMessage: function () {

    let share_key = this.data.key ? this.data.key : '';
    let share_path = '';
    if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
      share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
    } else {
      share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
    }
    return {
      title: '【仅需￥' + this.data.goods_detail.goods_info.goods_promotion_price + '】' + this.data.goods_detail.goods_info.goods_name,
      imageUrl: this.data.goods_detail.goods_info.share_img,
      path: share_path
    }
  }
})